/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.atguigu.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.http.HttpStatus;

import java.util.HashMap;
import java.util.Map;

/**
 * 返回数据
 *
 * @author Mark sunlightcs@gmail.com
 */
public class R_1 extends HashMap<String, Object> {
	private static final long serialVersionUID = 1L;

//	// 利用fastjson进行逆转
	public <T> T getData(TypeReference<T> typeReference) {
		Object data = get("data"); // get(data)默认是map类型。
		String s = JSON.toJSONString(data);
		T t = JSON.parseObject(s, typeReference);

		return t;
	}

	public <T> T getData(String key, TypeReference<T> typeReference) {
		// 根据键名获取对应的值（默认是map类型）
		Object data = get(key);
		if (data == null) {
			return null; // 或抛出异常，根据业务需求处理
		}
		// 转换为JSON字符串
		String jsonStr = JSON.toJSONString(data);
		// 解析为目标类型
		T result = JSON.parseObject(jsonStr, typeReference);
		return result;
	}

	public R_1 setData(Object data) {
		put("data", data);
		return this;
	}

	public R_1() {
		put("code", 0);
		put("msg", "success");
	}
	
	public static R_1 error() {
		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常，请联系管理员");
	}
	
	public static R_1 error(String msg) {
		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
	}
	
	public static R_1 error(int code, String msg) {
		R_1 r = new R_1();
		r.put("code", code);
		r.put("msg", msg);
		return r;
	}

	public static R_1 ok(String msg) {
		R_1 r = new R_1();
		r.put("msg", msg);
		return r;
	}
	
	public static R_1 ok(Map<String, Object> map) {
		R_1 r = new R_1();
		r.putAll(map);
		return r;
	}
	
	public static R_1 ok() {
		return new R_1();
	}

	public R_1 put(String key, Object value) {
		super.put(key, value);
		return this;
	}
	public  Integer getCode() {

		return (Integer) this.get("code");
	}

}
